<template>
  <div class="container">

    <!-- 面包屑导航 -->
    <navbar></navbar>
    <!--
    <div class="content page-title">
      <h2>标签管理</h2>
    </div>
    -->
    <div v-bind:class="[{'program' :pageType === 1}]">
    <div class="program-left">
    <div class="content">
      <h2 class="padding">{{ pageTitle }}</h2>
      <basic-information ref="basicInformation" :rQueryObj="rQuery" :pDetails="details" @basicForm="resBasicForm"></basic-information>
    </div>
    <div class="content">
        <h3>{{ ruleTitle }}</h3>
        <p class="size12 title_color" v-if="pageType === 1">创建规则</p>
        <p class="size12" v-if="pageType === 1">在全部用户中，将满足以下条件的用户分为 X 个分层，系统会按照以下自定义分层的顺序进行用户匹配，同一用户会被优先匹配在顺序靠前的分层中</p>
        <setup-rule ref="setupRule" :typeStr='pageType' :rQueryObj="rQuery" :pDetails="details" @ruleForm="resRuleForm"></setup-rule>
    </div>
    </div>
    <div class="program-right" v-if="pageType === 1">
      <div class="program-right-title">预估人数</div>
      <div class="program-right-select">
        <el-select
            v-model="estimateType"
            placeholder="请选择"
            filterable
            clearable
        >
          <el-option
              v-for="item in dictionaries.tag_estimate_type"
              :key="item.dictId"
              :label="item.dictName"
              :value="item.dictId"
          >
          </el-option>
        </el-select>
      </div>
      <div class="program-right-button">
        <el-button type="primary" plain @click="() => submit('estimate')" :loading="loading">预估</el-button>
      </div>
    </div>
    </div>
    <div class="operation-button">
      <el-button plain @click="() => onMotivation('delete')" v-if="details.name">删除</el-button>
      <el-button type="success" @click="() => onMotivation('enable')" v-if="details.status === 2">启动</el-button>
      <el-button type="success" @click="() => onMotivation('disable')" v-if="details.status === 1">暂停</el-button>
      <el-button type="primary" @click="() => onMotivation('submit')" :loading="loading">提交</el-button>
      <el-button plain @click="() => onMotivation('cancel')">取消</el-button>
    </div>

    <!--========================== el-dialog =================================-->
    <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :width="dialog.width"
        :append-to-body="true"
    >
      <!-- 预估-->
      <template>
        <div>
<!--          <span>这是一段信息</span>-->
          <el-table
              class = "estimate-data-list"
              :data="estimateDataList"
              style="width: 100%">
            <el-table-column
                prop="tagTierName"
                label="客户分层">
            </el-table-column>
            <el-table-column label="预估人数/占比">
              <template slot-scope="scope">
                <span>{{scope.row.customerCount}}</span>
                <span>（{{scope.row.rate === '-' ? 0 : scope.row.rate}}）</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-dialog>
    <!--=========================== el-dialog end================================-->

  </div>
</template>

<script>
import navbar from '@/components/navbar.vue'
import BasicInformation from './components/BasicInformation.vue'
import CommonTable from './components/CommonTable.vue'
import SetupRule from './components/SetupRule.vue'
import GraphicContent from './components/GraphicContent.vue'
import common from './mixins/common'

export default {
  mixins: [common],
  components: {
    navbar,
    BasicInformation,
    CommonTable,
    SetupRule,
    GraphicContent
  },
  data () {
    return {
      loading: false,
      pageTitle: '添加标签',
      details: {
        status: 999, // 状态（1-启用，2-暂停，3-回收站）999-添加
        createWay: 1 // 创建方式
      }, // 标签详细信息
      pageType: 1, // 1、 program 程序，默认为 新增程序化标签, 新增分群， 2、diy 自定义  diy
      dialog: { visible: false, title: '编辑', width: '640px', type: '', row: {}, batch: false },
      category: '',
      estimateType: '', // 预估计算方式（字典：tag_estimate_type）
      estimateDataList: '',
      salesAuthority: [{ reallyName: 'reallyName', id: 123 }],
      rQuery: {}, // 路由参数
      resFormData: {
        basicInformation: {},
        setupRule: {}
      },
      ruleTitle: '标签规则'
    }
  },
  mounted () {
    this.$nextTick(_ => {
      // console.log('mounted this.$nextTick')
      this.changeBreadcrumbTitle()
    })
  },
  created () {
    // console.log(process.env)
    const rQuery = this.$route.query
    this.rQuery = rQuery
    if (rQuery.state !== 'add') {
      this.getDetails(rQuery.labelId) // 详细信息查询接口
    }
    setTimeout(() => {
      this.onModifyText() // 修改文案
    }, 500)
  },
  watch: {
    /* 监听*/
    $route () {
      this.changeBreadcrumbTitle()
    }
  },
  methods: {
    // 详细信息查询接口
    getDetails () {
      let id, methodFun
      if (this.rQuery.labelId) {
        id = this.rQuery.labelId
        methodFun = this.$api.tagDetails
      } else {
        id = this.rQuery.groupId
        methodFun = this.$api.classifyGroupDetails
      }
      // console.log(this.rQuery)
      if (!id) {
        /*
        this.$notify({
          title: '提示',
          message: '地址有误',
          type: 'warning'
        })
        */
        this.$message.warning('地址有误！')
        setTimeout(() => {
          this.$router.go(-1)
        }, 1000)
        // return this.$message.warning('地址有误！')
      }
      const params = { id }
      methodFun(params).then((res) => {
        if (res.code === 0) {
          // this.$message.success('操作成功！')
          this.details = res.data
          // this.details = Object.assign(this.details, res.data)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 修改文案
    onModifyText () {
      const rQuery = this.$route.query
      if (rQuery.type === 'group') {
        this.ruleTitle = '人群规则'

        const modifyText = '添加、编辑分群'
        const topbarWrapper = document.getElementsByClassName('topbar-wrapper')[0]
        const topbarWrapperTitle = topbarWrapper.getElementsByClassName('title')[0]
        topbarWrapperTitle.innerText = modifyText

        const breadcrumb = document.getElementsByClassName('breadcrumb')[0]
        const breadcrumbLi = breadcrumb.getElementsByTagName('li')[1]
        breadcrumbLi.innerText = modifyText
      }
    },
    changeBreadcrumbTitle () {
      /*
      1、三个类型页面使用
      2、diy - 新增自定义标签，group - 新增分群， 默认为 新增程序化标签
       */
      const rQuery = this.$route.query
      this.rQuery = rQuery
      // console.log(this.rQuery)
      const breadcrumb = document.getElementsByClassName('breadcrumb')
      if (breadcrumb) {
        const breadcrumbUl = breadcrumb[0].getElementsByTagName('ul')
        if (breadcrumbUl) {
          const breadcrumbLi = breadcrumbUl[0].getElementsByTagName('li')
          if (breadcrumbLi) {
            const breadcrumbSpan = breadcrumbLi[1].getElementsByTagName('span')
            if (breadcrumbSpan) {
              const isAdd = rQuery.state === 'add'
              if (rQuery.type === 'diy' || rQuery.createWay === '2') {
                breadcrumbSpan[0].innerHTML = isAdd ? '新增自定义标签' : '修改自定义标签'
                this.pageTitle = isAdd ? '新增自定义标签' : '修改自定义标签'
                this.pageType = 2
              } else if (rQuery.type === 'group') {
                breadcrumbSpan[0].innerHTML = isAdd ? '新增分群' : '修改分群'
                this.pageTitle = isAdd ? '新增分群' : '修改分群'
                this.pageType = 1
              } else {
                breadcrumbSpan[0].innerHTML = isAdd ? '新增程序化标签' : '修改程序化标签'
                this.pageTitle = isAdd ? '新增程序化标签' : '修改程序化标签'
                this.pageType = 1
              }
            }
          }
        }
      }
    },
    // 表格 查看 按钮
    onShowDialog (row) {
      const dialog = {
        visible: true,
        title: '预估人数',
        type: '预估',
        width: '600px',
        row,
        batch: false,
        subTitle: '(时间：2022年6月)'
      }
      this.dialog = dialog
      // console.log('showDetail 查看', this.dialog)
    },
    // 删除，暂停，启用，提交，取消
    onMotivation (method) {
      const rQuery = this.rQuery
      const time = new Date().getTime()
      let confirmTitle, confirmMessage
      const detailsTitle = this.details.name || ''
      switch (method) {
        case 'delete': // 删除
          confirmTitle = '删除'
          confirmMessage = `是否删除${detailsTitle}`
          break
        case 'disable': // 暂停
          confirmTitle = '暂停'
          confirmMessage = `是否暂停${detailsTitle}`
          break
        case 'enable': // 启用
          confirmTitle = '启用'
          confirmMessage = `是否启用${detailsTitle}`
          break
        case 'submit': // 提交
          confirmTitle = '提交'
          confirmMessage = '是否提交当前内容？'
          break
        default: // 取消 cancel
          confirmTitle = '取消'
          // confirmMessage = `是否取消【${detailsTitle}】编辑`
          confirmMessage = `是否取消编辑`
          console.log(method)
      }
      this.$confirm(confirmMessage, confirmTitle, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // if (!method) { this.$router.go(-1) }
        switch (method) {
          case 'delete': // 删除
            this.onDelete(method)
            break
          case 'disable': // 暂停
            this.onEnableDisable(method)
            break
          case 'enable': // 启用
            this.onEnableDisable(method)
            break
          case 'submit': // 提交
            this.submit(method)
            break
          default: // 取消 cancel
            if (rQuery.type === 'group') {
              this.$router.push({ path: '/LabelGroup/clientsBands', query: { time }})
            } else {
              this.$router.push({ path: '/LabelGroup/labelmanage', query: { time }})
            }
        }
        // methodFun(method)
      }).catch(() => {
        if (method === 'submit') {
          console.log(`已取消${confirmTitle}`)
        } else {
          this.$message({
            type: 'info',
            // message: `已取消${confirmTitle}`
            message: `已取消`
          })
        }
      })
    },
    onDelete (method) {
      const rQuery = this.rQuery
      const time = new Date().getTime()
      let id, methodFun
      if (rQuery.labelId) {
        id = rQuery.labelId
        methodFun = this.$api.tagDelete
      } else {
        id = rQuery.groupId
        methodFun = this.$api.classifyGroupDelete
      }
      const params = { id }
      methodFun(params).then((res) => {
        if (res.code === 0) {
          this.$notify({
            title: '成功',
            message: '操作成功!',
            type: 'success',
            duration: 3000
          })
          if (rQuery.groupId) {
            this.$router.push({ path: '/LabelGroup/clientsBands', query: { time }})
          } else {
            this.$router.push({ path: '/LabelGroup/labelmanage', query: { time }})
          }
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onEnableDisable (method) {
      const rQuery = this.rQuery
      let methodFun, tipsText
      const params = { id: '' }
      switch (method) {
        case 'enable': // 暂停
          // tipsText = `操作成功！`
          tipsText = `启用成功！`
          if (rQuery.type === 'group') {
            params.id = rQuery.groupId
            methodFun = this.$api.classifyGroupEnable
          } else {
            params.id = rQuery.labelId
            methodFun = this.$api.tagEnable
          }
          break
        case 'disable': // 启用
          // tipsText = `操作成功！`
          tipsText = `暂停成功！`
          if (rQuery.type === 'group') {
            params.id = rQuery.groupId
            methodFun = this.$api.classifyGroupDisable
          } else {
            params.id = rQuery.labelId
            methodFun = this.$api.tagDisable
          }
          break
        default: // 其它
          return console.log('method参数有误！')
      }
      methodFun(params).then((res) => {
        if (res.code === 0) {
          this.details.status === 1 ? this.details.status = 2 : this.details.status = 1
          this.$message.success(tipsText)
          // 标签详细信息查询接口
          // this.getTagDetails(labelId)
          // this.$router.go(0)
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    resBasicForm (data, isSubmit) {
      this.resFormData.basicInformation = { data, isSubmit }
    },
    resRuleForm (data, isSubmit) {
      this.resFormData.setupRule = { data, isSubmit }
    },
    submit (model) {
      // model estimate 为 预估， submit 为提交
      this.$refs.basicInformation.submitForm()
      this.$refs.setupRule.submitForm()
      // debugger
      const rQuery = this.rQuery
      const basicInformation = this.resFormData.basicInformation
      const setupRule = this.resFormData.setupRule
      let isAction = false
      if (basicInformation.isSubmit && setupRule.isSubmit) { isAction = true }
      // if (!isAction) { return this.$message.warning('资料未填写完善！') }
      if (!isAction) { return console.log('资料未填写完善！') }
      if (setupRule.data.dynamicTags.length === 0) { return this.$message.warning('需要添加分层！') }
      // const fourthColumnList = document.getElementById('fourth-column-list')
      const tempParamsObj = {
        status: 1, // 状态（1-启用，2-暂停，3-回收站）
        createWay: rQuery.createWay === '2' ? '2' : '1', // 创建方式（字典：customer_tag_type，1-程序化标签，2-自定义标签）
        updateWay: setupRule.data.updateWay, // 更新方式（字典：customer_tag_refresh_type，1-例行，2-手动）
        tagTierList: setupRule.data.dynamicTags // 标签分层请求参数
      }
      const tempParams = Object.assign({}, tempParamsObj, basicInformation.data)

      // delete params.id
      const orgCodesTemp = []
      tempParams.orgCodes.forEach(it => {
        orgCodesTemp.push(it[it.length - 1])
      })
      tempParams.orgCodeItem = tempParams.orgCodes
      tempParams.orgCodes = orgCodesTemp
      // params.tagTierList = [ { id: 13, name: '消费大牛', desc: '30天内，消费4000元为消费大牛', sort: 2, tagRuleCodes: ['customer_user', 'base_info', 'tall'], ruleValues: [['30'], ['5000'] ] }]
      // console.log(setupRule.data.dynamicTags)
      tempParams.tagTierList = setupRule.data.dynamicTags

      let methodFun
      const params = Object.assign({}, JSON.parse(JSON.stringify(tempParams)))
      params.tagTierList.forEach(it => {
        delete it.addressList
        delete it.columnList
        delete it.expression
        delete it.expressionArr
        delete it.index
        delete it.paramTypeList
        delete it.selectList
        if (rQuery.type === 'diy' || rQuery.createWay === '2') {
          delete it.ruleCodes // 人群类型代码
          delete it.ruleValues // 规则参数 标签/人群
          delete it.groupDesc
          it.tagRuleCodes = [''] // 标签类型代码 标签
        } else {
          const tempRuleValues = []
          if (it.ruleValues) {
            it.ruleValues.forEach(item => { if (item[0] !== '') { tempRuleValues.push(item) } })
          }
          it.ruleValues = tempRuleValues
        }
      })

      if (model === 'submit') {
        if (rQuery.type === 'group') { methodFun = this.$api.classifyGroupAddOrUpdate } else { methodFun = this.$api.tagAddOrUpdate }
      } else {
        params.estimateType = this.estimateType // 预估计算方式（字典：tag_estimate_type）
        if (params.estimateType === '' || params.estimateType === undefined) { return this.$message.warning('请选择预估计算方式！') }
        if (rQuery.type === 'group') {
          params.tagClassifyId = -1
          // params.dynamicTags.forEach(item => { item.tagRuleCodes.splice(2, 1) })
          // return console.log(params)
          methodFun = this.$api.classifyGroupEstimate
        } else {
          methodFun = this.$api.tagEstimate
        }
        this.loading = true
      }
      // return console.log(params)
      methodFun(params).then((res) => {
        this.loading = false
        if (res.code === 0) {
          // this.$message.success('操作成功！')
          if (model === 'submit') {
            this.$notify({
              title: '成功',
              message: '操作成功!',
              type: 'success',
              duration: 3000
            })
            console.log(res.data)
            // const query = {...this.$route.query,labelId:res.data}
            // delete query.state
            // this.$router.push({ path: "/LabelGroup/labelAdd", query })
            const time = new Date().getTime()
            if (rQuery.type === 'group') {
              this.$router.push({ path: '/LabelGroup/clientsBands', query: { time }})
            } else {
              this.$router.push({ path: '/LabelGroup/labelmanage', query: { time }})
            }
          } else {
            this.estimateDataList = res.data
            this.onShowDialog()
            console.log('预估')
          }
        }
      }).catch((err) => {
        this.loading = false
        console.log(err)
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import './assets/common';
///deep/ .el-table th > .cell { text-align: unset; }
.content{
  padding-bottom: 10px!important;
}
h2 {
  position: relative;
  margin-bottom: 21px;
  padding-left: 11px;
  &:before {
    position: absolute;
    top: 4px;
    left: 0;
    display: inline-block;
    content: '';
    width: 4px;
    height: 17px;
    background-color: #2d7edf;
  }
}
.program:after, .program-left:after, .program-right:after {
  clear: both;
  display: table;
  content: '';
}
.program{
  //width: 100%;
   display: flex;
  .program-left, .program-right{
    float: left;
  }
  .program-left{
    min-width: 620px;
    width: calc(100% - 420px);
  }
  .program-right{
    width: 400px;
    margin-left: 15px;
    margin-bottom: 18px;
    padding: 15px;
    background-color: #ffffff;
    .program-right-title{
      font-size: 18px;
      font-weight: 400;
      color: #333333;
      margin-bottom: 26px;
    }
    .program-right-select{
      margin-bottom: 26px;
    }
    .program-right-button{
      .el-button{
        width: 128px;
        height: 36px;
        background: #4168E7;
        color: #ffffff;
      }
    }
  }
}
.operation-button{
  margin-bottom: 20px;
  .el-button{
    width: 120px;
    height: 36px;
  }
  .el-button--default{
    background-color: #FFFFFF;
    border: 1px solid #4168E7;
    color: rgba(65, 104, 231, 1);
  }
  .el-button--primary{
    background-color: #4168E7;
    border: 1px solid #4168E7;
    color: #ffffff;
  }
  .el-button--success{
    background-color: rgba(18, 171, 98, 1);
    border: 1px solid rgba(18, 171, 98, 1);
  }
}
.size12{
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #999999;
}
.title_color{
  color: #333333;
}

.estimate-data-list{
  :deep(.el-table__header-wrapper .el-table__header .has-gutter .el-table__cell){
    color: rgba(33, 33, 33, 1);
    background-color: rgba(248, 248, 249, 1);
    &:nth-child(2){
      text-align: right;
    }
  }
  :deep(.el-table__body-wrapper .el-table__body .el-table__row .el-table__cell){
    &:nth-child(2){
      text-align: right;
    }
  }
}
</style>
